package com.example.common.result;

import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author benjamin_5
 * @Description 统一返回体
 * @date 2023/2/22
 */
@Data
@NoArgsConstructor
public class R<T> {

    /**
     * 状态码
     */
    private int code;
    /**
     * 返回信息
     */
    private String message;
    /**
     * 承载数据
     */
    private T data;
    /**
     * 是否成功 true是 false否
     */
    private boolean success;

    private R(int code, T data, String message) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.success = code == ResultCode.SUCCESS.code;
    }

    private R(int code, String message){
        this.code = code;
        this.message = message;
        this.data = null;
        this.success = code == ResultCode.SUCCESS.code;
    }

    private R(ResultCode code, String message){
        this.code = code.code;
        this.message = message;
        this.data = null;
        this.success = code == ResultCode.SUCCESS;
    }

    public static <T> R<T> data(int code, T data, String message){
        return new R(code, data, data == null ? "数据为空" : message);
    }

    public static <T> R<T> data(ResultCode code, T data, String message){
        return new R(code.code, data, data == null ? "数据为空" : message);
    }

    public static <T> R<T> data(T data, String message){
        return data(ResultCode.SUCCESS, data, message);
    }

    public static <T> R<T> data(T data){
        return data(data, "操作成功");
    }

    public static <T> R<T> success(String message){
        return new R(ResultCode.SUCCESS, message);
    }

    public static <T> R<T> fail(String message){
        return new R(ResultCode.FAIL, message);
    }

    public static <T> R<T> fail(int code, String message){
        return new R(code, message);
    }

    public static <T> R<T> status(boolean success){
        return success ? success("操作成功") : fail("操作失败");
    }
}
